package com.zklh.leetcode.interviewTop150;

import java.util.Arrays;

/**
 * 生命游戏算法实现
 *
 * @Author tongnan
 * @Date 2024/6/21
 * @Version 1.0
 */
public class Solution289 {
    public void gameOfLife(int[][] board) {
        int[][] directs = new int[][]{
                {-1, -1},
                {0, -1},
                {1, -1},
                {1, 0},
                {1, 1},
                {0, 1},
                {-1, 1},
                {-1, 0}
        };
        // 定义标记 2  为 源数字是 0, 变为1,  标记3为 源数字是 1 变为 0
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                // 存活
                int surviveCount = 0;
                for (int[] direct : directs) {
                    if (i + direct[0] < 0 || i + direct[0] >= board.length || j + direct[1] < 0 || j + direct[1] >= board[i].length) {
                        continue;
                    }
                    if (board[i + direct[0]][j + direct[1]] == 1 || board[i + direct[0]][j + direct[1]] - 2 == 1) {
                        surviveCount+=1;
                    }
                }
                if (surviveCount < 2 && board[i][j] == 1) {
                    board[i][j] = 3;
                }if (surviveCount == 3 && board[i][j] == 0) {
                    board[i][j] = 2;
                } if (surviveCount > 3 && board[i][j] == 1) {
                    board[i][j] = 3;
                }
            }
        }
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (board[i][j] == 3) {
                    board[i][j] = 0;
                } else if (board[i][j] == 2) {
                    board[i][j] = 1;
                }
            }
        }
    }

    public static void main(String[] args) {
        Solution289 solution289 = new Solution289();
        int[][] board = {{0,1,0},{0,0,1},{1,1,1},{0,0,0}};
        solution289.gameOfLife(board);
        System.out.println(Arrays.deepToString(board));
    }
}